package com.hyper_yang._01_jdbc.dbutils;

import com.hyper_yang._01_jdbc.pojo.Account;
import com.hyper_yang._01_jdbc.utils.JDBCUtil;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;
import org.junit.jupiter.api.Test;

import java.sql.Connection;
import java.util.List;

public class DQLTest {
    @Test
    public void testSelectOne() throws Exception {
        // todo: 查询一个数据，封装一个对象
        Connection connection = JDBCUtil.getConnection();
        QueryRunner queryRunner = new QueryRunner();
        String sql = "select id,name,balance from t_account where id = ?";
        // todo: new BeanHandler<>(类对象) 将查询的 ResultSet结果集封装指定的一个对象
        Account account = queryRunner.query(connection, sql, new BeanHandler<>(Account.class), 3);
        System.out.println(account);
        connection.close();
    }

    @Test
    public void testSelectMore() throws Exception {
        // todo: 查询多个数据，封装一个集合
        Connection connection = JDBCUtil.getConnection();
        QueryRunner queryRunner = new QueryRunner();
        String sql = "select id,name,balance from t_account";
        // todo: new BeanListHandler<>(类对象) 将查询的 ResultSet结果集封装成 List集合，泛型是类对象的类型
        List<Account> accountList = queryRunner.query(connection, sql, new BeanListHandler<>(Account.class));
        accountList.forEach(System.out::println);
        connection.close();
    }

    @Test
    public void testSelectOneResult() throws Exception {
        // todo: 查询 t_account里有多少个信息
        Connection connection = JDBCUtil.getConnection();
        QueryRunner queryRunner = new QueryRunner();
        String sql = "select count(*) from t_account";
        // todo: new ScalarHandler<>() 返回的是单个结果
        Object query = queryRunner.query(connection, sql, new ScalarHandler<>());
        System.out.println(query);

        connection.close();
    }
}
